<?php
namespace app\index\controller;

use app\common\controller\PayBase;
use think\Db;
use think\Request;

class Pay extends PayBase
{

    public function __construct()
    {
        parent::__construct();
    }

    public function callback()
    {
        @file_put_contents('build.txt', json_encode($_POST) . "\n", FILE_APPEND);
        Db::startTrans();
        $account_id = input('post.account') ? intval(input('post.account')) : 0;
        $type = input('post.type') ? input('post.type') : '';
        $money = input('post.money') ? floatval(input('post.money')) : 0;
        $time = input('post.time') ? input('post.time') : '';
        if ($time) $time = substr($time, 0, 10);
        $original = input('post.');

        if ($type && $money && $time && $account_id) {
           

            $five_ago = strtotime(date('Y-m-d H:i:s', $time) . ' -5 min');
            //更新用户订单、金额、打码量等相关信息
            $account = Db::name('code_account')->where('id', $account_id)->value('name');

            $order_info = Db::name('chongzhi_list')
                ->where(['je' => $money, 'openren' => $account, 'liuyan' => $type, 'zt' => 0, 'czclass' => 1])
                ->whereTime('cztime', 'BETWEEN', [$five_ago, $time])
                ->find();
            if (!$order_info) return packJson('', '无有效的订单信息', 500);

            $user_info = Db::name('username')->where('username', $order_info['username'])->find();
            $dml_set = Db::name('xt_dmsz')->where('id', 1)->find();
            $xtcz = Db::name('xt_chongzhi')->where('id', 1)->find();
            if ($xtcz['dmopen'] == 1) {
                $dmls = ($order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je']+ $order_info['method_money']) * $dml_set['xscz_dmbs'];
            } else {
                $dmls = $order_info['je'] * $dml_set['xscz_dmbs'];
            }
            //充值后账户总金额
            $czhje = $order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je'] + $user_info['je'] + $order_info['method_money'];
            //充值总金额
            $czzje = $order_info['je'] + $user_info['czzje'];
            //用户当前打码量
            $dml = $user_info['dml'] + $dmls;

            try {
            	if(!model('ChongzhiList')->updateRechargeInfo($order_info['ddbh'], '', 1, $czhje, time())){
            		
            	};
            	Db::name('response_code')->where('remark', $order_info['ddbh'])->update(['status' => 1, 'remark' => '']);
                model('Username')->upUserXsczInfo($czhje, $dml, $czzje, $order_info['username']);
                
                $fav_money = $order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['method_money'];

                //满送金额，等级赠送金额，充值方案赠送金额
                $extcj = array(
                    'username'=>$user_info['username'],
                    'user_class'=>$user_info['us_class'],
                    'fstime'=>time(),
                    'czadmin' => '系统赠送',
                );
                $cjhje = floatval($order_info['je']) + floatval($user_info['je']) + floatval($order_info['hy_msje']);
                if( floatval($order_info['hy_msje']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值满送金额';
                    $extcj['cjje'] = $order_info['hy_msje'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($order_info['hy_zsje']);
                if( floatval($order_info['hy_zsje']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值等级赠送金额';
                    $extcj['cjje'] = $order_info['hy_zsje'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($order_info['method_money']);
                if( floatval($order_info['method_money']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值方案赠送金额';
                    $extcj['cjje'] = $order_info['method_money'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }

				Db::name('username')->where('username',$order_info['username'])->setInc('cz_num');
                $data = array('username' => $order_info['username'], 'test' => "您账户充值金额：{$order_info['je']}，赠送金额：{$fav_money}。已充值到账，请注意查收！", 'xx_time' => time(), 'ifdq' => 0);
                Db::name('xiaoxi')->data($data)->insert();

                Db::commit();
                return packJson($original, '', 200);
            } catch (\Exception $e) {
                Db::rollback();
                return packJson('', '操作失败请重试', 505);
            }
        } else {
            return packJson('', '参数无效或不完整', 500);
        }
    }

    public function buildCode()
    {
        Db::startTrans();
        //接收数据
        $user = cookie('username', '');
        $password = cookie('password', '');
        $username = input('post.username', '');
        $pay_type = input('post.type', '');
        $money = input('post.money', '');

        $username = strtolower($username);

        //验证用户信息
        if (!$user || !$username || ($user != $username)) {
            return packJson('', '用户身份验证失败', 500);
        }
        $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username' => $username, 'password' => $password])->find();
        if (!$user_info) {
            return packJson('', '用户身份验证失败', 500);
        }
        if ($user_info['swzh'] == 1) {
            return packJson('', '试玩账号无法充值', 500);
        }
        if ($user_info['nbzh'] == 1) {
            return packJson('', '内部账号不支持线上充值', 500);
        }
        //验证金额
        if ($money <= 0) {
            return packJson('', '输入的金额无效', 500);
        }
        if (!in_array($pay_type, ['wechat', 'alipay'])) {
            return packJson('', '无效的充值方式', 500);
        }

        if( 'wechat'==$pay_type ){
            $remark = '微信二维码转账';
        }else{
            $remark = '支付宝二维码转账';
        }

        //生成订单号
        $order_sn = 'T' . str_pad($user_info['id'], 5, '0', STR_PAD_LEFT) . time() . rand(111, 999);
        try {
            $online_ac = Db::name('code_account')->alias('ca')
                ->join('__RESPONSE_CODE__ rc', 'rc.account=ca.id')
                ->where(['ca.type' => $pay_type, 'ca.lock' => 0, 'ca.status' => 0, 'rc.status' => 1, 'rc.region' => $money])
                ->limit(1)
                ->find();
            if (!$online_ac['id']){
                return packJson('', '当前支付人数过多请稍后重试', 500);
            }

            Db::name('response_code')->where('id', $online_ac['id'])->update(['status' => 0, 'remark' => $order_sn]);
            $code = Db::name('response_code')->alias('rc')
                ->field('rc.*,ca.name,ca.max_je')
                ->join('__CODE_ACCOUNT__ ca', 'ca.id=rc.account')
                ->where('rc.id', $online_ac['id'])
                ->find();
            if (empty($code)) return packJson('', '当前支付人数过多请稍后重试', 500);

            $method = Db::name('pay_method')->find($online_ac['method_id']);
            $method_money = 0.00;
            if( !empty($method) && floatval($method['money']) > 0 ){
                if( 0==intval( $method['method'] ) ){
                    //金额
                    $method_money = $method['money'];
                }else{
                    //比例
                    $method_money = floatval($money) * floatval($method['money']) / 100;
                }
            }
            $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));

            $je = $code['max_je'] - $code['money'];
            Db::name('code_account')->where('id', $code['account'])->update(['max_je' => $je]);
            if ($code['max_je'] <= $money) {
                if ($pay_type == 'wechat') {
                    return packJson('', '微信充值已达最大限额，请更换其他方式充值', 500);
                }
                if ($pay_type == 'alipay') {
                    return packJson('', '支付宝充值已达最大限额，请更换其他方式充值', 500);
                }
            }
            if (!$code) {
                return packJson('', '当前支付人数过多请稍后重试', 500);
            }
            //$id = Db::name('response_code')->getLastInsID(); 
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();;
            return packJson('', '生成失败请重试', 500);
        }


        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->find();
        if ($harassment['open'] > 0) {
            $nowys = time() - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username', $username)->where('cztime', '>', $nowys)->find();
            if ($old_czjl['id'] > 0) {
                return packJson('', "系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！", 500);
            }
        }

        //计算优惠金额
        $msje = $msbs = 0;
        $cz_set = Db::name('xt_chongzhi')->find();
        $user_class = Db::name('us_class')->where('id', $user_info['us_class'])->find();
        $zsje = $code['money'] * $user_class['czzsbl'] / 100;
        $zsbs = $user_class['czzsbl'];
        if ($money >= $cz_set['xscz_je']) {
            $msje = $code['money'] * $cz_set['xscz_zs'] / 100;
            $msbs = $cz_set['xscz_zs'];
        }

		$u = Db::name('username')->where('username',$username)->value('je');
        //插入充值信息
        model('ChongzhiList')->setTransRechargeInfo($order_sn, $code['money'], $username, 0, 0, 1, $remark, time(), $code['name'], '二维码回调', get_ip(), 0, $pay_type, $zsje, $zsbs, $msje, $msbs, $user_info['us_class'],'',1,$method_money,$u);

        return packJson($code, '', 200);
    }

    public function getOrderInfoAjax(){
        exit;
        if (!Request::instance()->isAjax()) return packJson('', '非法请求', 500);

        $account = input('post.account') ? intval(input('post.account')) : 0;
        $type = input('post.type') ? input('post.type') : '';
        $money = input('post.money') ? floatval(input('post.money')) : 0;

        if ($type && $money && $account) {
            $five_ago = strtotime(date('Y-m-d H:i:s', time()) . ' -5 min');
            $status = Db::name('chongzhi_list')
                ->where(['je' => $money, 'openren' => $account, 'liuyan' => $type, 'czclass' => 1])
                ->whereTime('cztime', 'BETWEEN', [$five_ago, time()])
                ->value('zt');

            if ($status === null) return packJson('', '无有效的订单信息', 500);
            if ($status == 1) {
                return packJson('', '支付成功', 200);
            } else {
                return packJson('', '订单待支付', 500);
            }
        }
        return packJson('', '参数无效或不完整', 500);
    }


    //定时清除线上微信支付宝待支付订单
    public function cleanLineOrderStatus(){
        $time = strtotime(date('Y-m-d H:i:s', time()) . ' -5 min');
        $order_sn_arr = Db::name('chongzhi_list')->where(['zt' => 0, 'czclass' => 1, 'from' => 1])->where('cztime', '<', $time)->column('ddbh');
        if( empty( $order_sn_arr ) ){
            echo '暂无线上微信,支付宝可清除'.PHP_EOL;
        }else{
            $order_sns = join(',', $order_sn_arr);
            Db::startTrans();
            try {
                Db::name('chongzhi_list')->where('ddbh', 'IN', $order_sns)->data(['zt' => 9])->update();
                Db::name('response_code')->where('remark', 'IN', $order_sns)->update(['status' => 1, 'remark' => '']);
                $max = Db::name('chongzhi_list')->where('ddbh', 'IN', $order_sns)->field('openren,je,liuyan')->find();
                $maxje = Db::name('code_account')->where(['type' => $max['liuyan'], 'name' => $max['openren']])->value('max_je');
                $je = $maxje + $max['je'];
                Db::name('code_account')->where(['type' => $max['liuyan'], 'name' => $max['openren']])->update(array('max_je' => $je));
                Db::commit();
                echo '清除线上微信,支付宝成功'.PHP_EOL;
            } catch (\Exception $e) {
                Db::rollback();
                echo '清除线上微信,支付宝失败'.PHP_EOL;
            }
        }
    }

    //定时清第三方支付订单
    public function cleanThirdOrderStatus(){
        $time = strtotime(date('Y-m-d H:i:s', time()) . ' -30 min');
        $order_sn_arr = Db::name('chongzhi_list')->where(['zt' => 0, 'czclass' => 1, 'from' => 0])->where('cztime', '<', $time)->column('ddbh');
        if( empty( $order_sn_arr ) ){
            echo '暂无第三方支付订单可清除'.PHP_EOL;
        }else{
            $order_sns = join(',', $order_sn_arr);
            if ( Db::name('chongzhi_list')->where(['ddbh'=>['IN', $order_sns]])->update(['zt' => 9]) ) {
                echo '清除第三方支付订单成功'.PHP_EOL;
            } else {
                echo '清除第三方支付订单失败'.PHP_EOL;
            }
        }
    }
//还原最大值
    public function MaximumReduction()
    {
        Db::name('code_account')->where('type', 'alipay')->update(['max_je' => '3000']);
        Db::name('code_account')->where('type', 'wechat')->update(['max_je' => '2000']);
        return '好啦';
    }
    //代理定时结算佣金 处理代理佣金的 6点

    public function agencySettlement()
    {

        $start = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));

        $end = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        $time = [$start, $end];
        if (strtotime(date('Y-m-d 05:55:00')) <= time() && strtotime(date('Y-m-d 06:10:00')) >= time()) {
            $agent = Db::name('agent_balance')
                ->where('add_time', 'between', $time)
                ->where('status', 0)
                ->field('agent,SUM(balance) as balance,status')
                ->group('agent')
                ->select();
            $ids = Db::name('agent_balance')
                ->where('add_time', 'between', $time)
                ->where('status', 0)
                ->column('id');
			$je = 0;
			$data=array();
            foreach ($agent as $value) {
                $je = Db::name('username')->where('username', $value['agent'])->value('je');
                $data = array('balance'=>sprintf("%.2f",$value['balance']),'agent'=>$value['agent'],'fyqje'=>sprintf("%.2f",$je),'add_time'=>time());
                Db::name('day_agent')->data($data)->insert();
            	Db::name('username')->where('username', $value['agent'])->update(['je' => ['exp',"je+{$value['balance']}"] , 'dlzyj' => ['exp',"dlzyj+{$value['balance']}"]]);
                //Db::name('username')->where('username', $value['agent'])->update(['je' => $je['je'] + $value['balance'], 'dlzyj' => $je['dlzyj'] + $value['balance']]);
            }

            foreach ($ids as $id) {
                Db::name('agent_balance')->where('id', $id)->update(['status' => 1]);
            }
            echo '派彩成功';
        } else {
            echo '时间没到，不能派彩哦！';
        }
    }


    //每天 #处代理结算的 5点
    public function agentSet()
    {
        $start = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $end = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        $time = [$start, $end];
        //$touzhu = Db::name('touzhu_list_ok')->where('tz_time', 'between', $time)->select();
        $touzhu = Db::name('touzhu_list_ok')->where('status',0)->where('tz_time', 'between', $time)->select();

        if (strtotime(date('Y-m-d 04:59:00')) <= time() && strtotime(date('Y-m-d 06:00:00')) >= time()) {
            foreach ($touzhu as $tz) {
                $kjjg = Db::name('kjjg_list')->where('czid', $tz['czid'])->where('qihao', $tz['qihao'])->find();

                $status = $this->dailijiesuan($tz['id'],$tz['username'], $tz['tzje'] - $tz['fdje'], $tz['qihao'], $tz['czid']);
                
                Db::name('touzhu_list_ok')->where('id', $tz['id'])->update(['status' => 1]);
                
            }
            echo '代理佣金成功';
         } else {
            echo '时间没到';
        } 

    }

    function dailijiesuan($id,$user, $tzje, $qihao, $czid, $xjrens = 'xjrens>=0', $consumer = '')
    {
        if (!$consumer) {
            $consumer = $user;
        }
        $chaxun = Db::name('username')->where('username', $user)->where($xjrens)->find();
        if ($chaxun['tjr'] != '') {
            static $i = 0;
            $one_1 = Db::name('username')->where('username', $chaxun['tjr'])->where('dl', 1)->find();
            if ($i == 0) {
                $dhujd = $tzje / 100 * ($one_1['fandian'] - 0);
                $fandian = $one_1['fandian'] - 0;
            } else {
                $dhujd = $tzje / 100 * ($one_1['fandian'] - $chaxun['fandian']);
                $fandian = $one_1['fandian'] - $chaxun['fandian'];
            }
            if($dhujd>0){
	            $cur_time = time();
	            $data = [
	                'agent' => $chaxun['tjr'],
	                'balance' => $dhujd,
	                'consumer' => $consumer,
	                'higher_agent' => $user,
	                'czid' => $czid,
	                'qihao' => $qihao,
	                'true_je' => $tzje,
	                'add_time' => $cur_time,
	                'status' => 0,
	                'ddid' => $id,
	                'fandian' =>$fandian
	            ];
	            Db::name('agent_balance')->data($data)->insert();
            }
            if ($one_1['tjr'] != '') {
                $i++;
                $this->dailijiesuan($id,$chaxun['tjr'], $tzje, $qihao, $czid, $xjrens = 'xjrens>0', $consumer);
            }

        }
    }
    /**
     * 72小时候自动删除试玩账号
     */
    public function deleteSwzh(){
    	$time = strtotime(date("Y-m-d",strtotime("-3 day")).' 23:59:59');
    	$name=array();
    	$sw = Db::name('xt_shiwan')->where('id',1)->find();
    	$touzhu = Db::name('touzhu_list_no')->select();
    	foreach ($touzhu as $tz){
    		if(strpos($tz['username'], $sw['qianzhui'])!==false){
    			$name[]= $tz['id'];
    		}
    	}
    	if(Db::name('touzhu_list_no')->where('id','IN',$name)->delete()){
    		echo '成功';
    	}
    	if(Db::name('username')->where('reg_time','<',$time)->where('swzh',1)->delete()){
    		Db::name('touzhu_list_sw')->where('tz_time','<',$time)->delete();
    		echo '删除成功';
    	}
    }
    

     /*  public function addTime(){
    	$czid = '46';
    	$arr = array();
    	for ($i=1;$i<88;$i++){
    		$time = strtotime(date('Y-m-d').'08:29:00');
    		$time = $time+540*($i-1);
    		$arr = array('czid'=>$czid,'qihao'=>$i,'jztime'=>date('H:i:s',$time));
    		if(Db::name('time')->insert($arr)){
    			echo 'ok';
	    	}else{
	    		echo 'no';
	    	}
    	} 


    }  */


}
